package com.me.waterphase.listener;

import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Contact;
import com.badlogic.gdx.physics.box2d.ContactImpulse;
import com.badlogic.gdx.physics.box2d.Manifold;
import com.badlogic.gdx.physics.box2d.WorldManifold;
import com.me.waterphase.listener.contact.FootContact;

public class GroundListener   {
	

	public static void beginContact(Contact contact, boolean _isA) {
		
		if((_isA && contact.getFixtureB().getUserData() == null) || (!_isA && contact.getFixtureA().getUserData() == null))
		{
			FootContact footContact;
			WorldManifold manif = contact.getWorldManifold();
			Vector2 direction = null;
			
			if(manif.getNumberOfContactPoints() > 0)
			{
				//Set the direction of the feet, that's perpendicular to the normal of the world manifold.
				Vector2 normal = manif.getNormal();
				
				//If the Y-axis is negative, the normal is calculated from the bottom fixture. Then inverses it.
				if(normal.y < 0)
				{
					normal.y *= -1;
					normal.x *= -1;
				}
				
				if(Math.abs(normal.y) < Math.abs(normal.x))
					direction = new Vector2(normal.x, normal.y);
				else			
					direction = new Vector2(normal.y, -normal.x);
			}
			
			//Increment the number of foot's contact of one or both fixtures.
			if(_isA)
			{
				footContact =((FootContact)contact.getFixtureA().getUserData());
				footContact.increment();
				
				if(direction != null)
					footContact.setDirection(direction.cpy());
			}
			else
			{
				footContact =((FootContact)contact.getFixtureB().getUserData());
				footContact.increment();
				footContact.setDirection(direction.cpy());
			}
		}
	}

	public static void endContact(Contact contact, boolean _isA) {
		
		//Do not have ground contact with the artifact.
		if((_isA && contact.getFixtureB().getUserData() == null) || (!_isA && contact.getFixtureA().getUserData() == null))
		{
			//Decrement the number of foot's contact of one or both fixtures.
			if(_isA)
				((FootContact)contact.getFixtureA().getUserData()).decrement();
			else
				((FootContact)contact.getFixtureB().getUserData()).decrement();
		}
	}
	
	public static void preSolve(Contact contact, Manifold oldManifold, boolean _isA) {
		contact.setEnabled(false);
	}

	public static void postSolve(Contact contact, ContactImpulse impulse, boolean _isA) {
		// TODO Auto-generated method stub
	}

}
